<template>
  <el-card shadow="never" class="content-wrap">
    <Header></Header>
    <div class="chat-box">
      <el-scrollbar :height=heightPX ref="scrollbar" @scroll="handleScroll">
        <div v-for="(item, index) in chatList" class="chat-item" :key="index">
          <div class="req-box">我：{{ item.req }}</div>
          <div class="res-box">
            <div v-show="item.res">
              开放蓝天 OpenBlueSky.cn:
            </div>
            <!-- <div class="answer" v-show="item.res"> -->
            <div class="answer" v-show="item.res">
              <!-- <div class="message" v-html="item.res"> -->
              <v-md-preview-html :html="mdi.render(item.res)" preview-class="vuepress-markdown-body"></v-md-preview-html>
              <!-- <div v-for="(item1, indexx) in chatListAry[index]" :key="indexx">
                <div v-if="indexx % 2 === 0">
                  {{ item1 }}
                </div>
                <div v-if="indexx % 2 !== 0" class="hljs-container" v-code>
                  <highlightjs language :code="item1"></highlightjs>
                </div>
              </div> -->
            </div>
            <div class="loading" v-show="currentIndex === index && !item.res">
              <div></div>
              <div></div>
              <div></div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="send-box">
      <el-input placeholder="发送消息" v-model="question" @keyup.enter="getAnswer"></el-input><el-button
        @click="getAnswer">开始聊天</el-button>
    </div>
    <div class="tip">本站点基于外部API二次开发，仅供学习 AI 使用，使用前请知晓 免责申明</div>
  </el-card>
</template>

<script  setup lang="ts">
import { watch, onDeactivated, onActivated, nextTick } from "vue";
import chatApi, { senMessage } from '@/api/chat'
import vCode from '@/utils/line';
import { getToken } from '@/utils'
import { useHistoryStore } from '@/stores/history'
// import func from 'vue-temp/vue-editor-bridge';
import bus from '@/utils/bus'
import { useRouter, onBeforeRouteUpdate } from 'vue-router';
import axios from "axios";
import mdi from "@/utils/mdRender"

import { fetchEventSource } from '@microsoft/fetch-event-source';





const route = useRoute()
const router = useRouter()
const historyStore = useHistoryStore()
const chatList: any = ref([])
// 用于保存答案分割后的数组，以便于制作代码块效果，区分开代码和普通文本
const chatListAry: any = ref([])
const title = ref()
let isPhone = ref() // 检测是否为移动端
let heightPX = ref() // 检测是否为移动端
let currentPath = ref("")
const message = ref('')
const currentIndex = ref(0)
const flag = ref(false)

const scrollbar = ref()
const isAutoScroll = ref(true)
let timer: any = null
const handleScroll = () => {
  isAutoScroll.value = false;
  clearTimeout(timer);
  timer = setTimeout(() => {
    isAutoScroll.value = true;
  }, 1000);
}

watch(() => message.value, (val) => {
  nextTick(() => {
    // 用户手动滚动就不执行
    if (!isAutoScroll.value) return;
    const scrollHeight = scrollbar.value.wrapRef.childNodes[0].scrollHeight;
    scrollbar.value.wrapRef.scrollTop = scrollHeight;
  });
}, { immediate: true, })

const destroyWatch = watch(() => router.currentRoute.value.path, (toPath) => {
  // const id = router.currentRoute.value.params.id
  const index = toPath.lastIndexOf('/');
  const id = toPath.substring(index + 1);

  setTimeout(() => {
    historyStore.historyChatList.map(item => {
      if (item.sessionId == id) {
        chatList.value = item.history
      }
    })
    currentIndex.value = chatList.value.length
    console.log(2222222222, chatList.value);

  }, 1000);

  //要执行的方法

  if (toPath == "/home") {
    console.log(11111);

  }
}, { immediate: true, })

onActivated(() => {
  chatList.value = []
  console.log(44444444);

})
// onDeactivated(() => {
//   destroyWatch()
// })


const controller = new AbortController();
fetchEventSource('http://localhost:8888/chatgpt/stream', {
  headers: {
    "third-session": getToken()
  },
  onmessage({ data }) {
    data = data.replaceAll('space:space', ' ')
    data = data.replaceAll('newline:newline', '\r\n')
    data = data.replaceAll('tabs:tabs', '\r\n')



    if (flag.value) { //结束会话就return
      return
    }


    if (data === 'event :end ') {
      flag.value = true;
      message.value = ""
      console.log("结束一次问话")
      loading.value = false;
      currentIndex.value = chatList.value.length
    } else {
      message.value += data;
      console.log(message.value);
      // chatList.value[chatList.value.length - 1].res = mdi.render(message.value.replace('MY:', ''));
      chatList.value[chatList.value.length - 1].res = message.value.replace('MY:', '');
    }
  },
  signal: controller.signal,
});

function eventSource() {
  // axios({
  //   method: 'get',
  //   url: 'http://localhost:8888/chatgpt/stream',
  //   onDownloadProgress: function ({ target }) {
  //     let responseText = target.responseText;
  //     console.log(responseText);

  //     if (responseText.startsWith('data:')) {
  //       responseText = responseText.slice(5);
  //     }

  //     if (responseText.endsWith(':end ')) {
  //       message.value = ""
  //       console.log("结束一次问话")
  //       currentIndex.value = chatList.value.length
  //       loading.value = false;
  //       return
  //     }

  //     message.value = responseText;
  //     chatList.value[chatList.value.length - 1].res = mdi.render(message.value)
  //   },
  // })
}


onMounted(() => {
  title.value = route.meta.title
  // 用于展示历史聊天记录
  // chatList.value = historyStore.historyChatList
  // chatListAry.value = historyStore.historyChatListAry
  if (route.query.que) {
    question.value = route.query.que as string
    getAnswer()
  }
  isPhone.value = _isMobile.value.isPhone
  heightPX.value = isPhone.value ? '400px' : '600px'
  //监听窗口变化，宽度小于600时鉴定为移动端
  console.log('初始化', isPhone.value)
  window.onresize = () => {
    return (() => {
      console.log('窗口变化', isPhone.value)
      if (window.innerWidth < 600) {
        isPhone.value = true
        heightPX.value = '400px'
      } else {
        heightPX.value = '600px'
      }
    })();
  };
});

const question = ref('')

const loading = ref(false)

function getAnswer() {
  if (!question.value || loading.value) {
    return
  }

  message.value = ""
  var strings = route.path.split('/');
  currentPath.value = strings[strings.length - 1]
  console.log(currentPath)
  const req = question.value
  flag.value = false; //开始一次新的问话
  senMessage({
    message: req,
    sessionId: currentPath.value
  })
  eventSource()

  chatList.value.push({
    req,
    res: ''
  })

  question.value = ''
  loading.value = true
  let chatObj = {
    chatList: chatList.value,
    chatListAry: chatListAry.value,
  }
  sessionStorage.setItem(currentPath.value, JSON.stringify(chatObj))


  // senMessage({
  //   message: req,
  //   sessionId: currentPath.value
  // })


  // chatApi.answer({
  //   message: req
  // }).then((res: any) => {
  //   // console.log(res)
  //   // 通过```拆分
  //   chatListAry.value.push(res.split('```'))
  //   chatList.value[chatList.value.length - 1].res = res.trim()
  //   let chatObj = {
  //     chatList: chatList.value,
  //     chatListAry: chatListAry.value,
  //   }
  //   sessionStorage.setItem(currentPath, JSON.stringify(chatObj))
  //   // 聊天记录存放于pinia
  //   // historyStore.pushHistory(chatList.value, chatListAry.value)
  //   loading.value = false
  // })
}
// 查看是否为移动端的方法
const _isMobile = computed(() => {
  var ua = navigator.userAgent,
    isWindowsPhone = /(?:Windows Phone)/.test(ua),
    isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
    isAndroid = /(?:Android)/.test(ua),
    isFireFox = /(?:Firefox)/.test(ua),
    isChrome = /(?:Chrome|CriOS)/.test(ua),
    isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
    isiPhone = /(?:iPhone)/.test(ua) && !isTablet,
    isPc = !isiPhone && !isAndroid && !isSymbian;
  return {
    isTablet: isTablet,
    isPhone: isiPhone || isAndroid,
    isAndroid: isAndroid,
    isPc: isPc
  };
})
</script>

<style lang="scss" scoped>
  ::v-deep .el-input__wrapper {
    background-color: var(--main-shallowbg-color) !important;
    border: 1px solid var(--main-bg-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  ::v-deep .el-input__inner {
    color: var(--main-font-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  ::v-deep .el-button {
    color: var(--main-font-color) !important;
    background: var(--main-shallowbg-color) !important;
    transition-property: all;
    transition-duration: 0.6s;
  }

  :deep(.github-markdown-body) {
    padding: 0;
  }
  :deep(.vuepress-markdown-body p) {
    margin: 0;
    line-height: 1.5;
  }

  .content-wrap {
    // padding: 20px 50px;

    .message {
      width: 100%;
      word-break: break-all;
      line-height: 1.3;
    }

    .chat-box {
      width: 90%;
      margin: 0 auto;
      background-color: var(--main-shallowbg-color) !important;
      transition-property: all;
      transition-duration: 0.6s;
      min-height: 400px;
      padding: 10px 0;

      .el-scrollbar {
        padding: 0 20px;
      }

      .chat-item {
        display: flex;
        flex-direction: column;

        .req-box {
          margin: 10px 0;
          align-self: end;
          color: #f7f8f8;
          background-color: #919292;
          padding: 7px 13px;
          border-radius: 15px;
          width: auto;
          max-width: 75%;
          display: inline-block;
        }

        .res-box {
          margin: 10px 0;
          align-self: start;
          padding: 12px 13px;
          border-radius: 15px;
          color: #595a5a;
          background-color: #ebebeb;
          width: auto;
          min-width: 50%;
          max-width: 75%;
          display: inline-block;

          .answer {
            margin-top: 12px;
            // white-space: pre-wrap;
          }
        }
      }
    }

    .send-box {
      width: 70%;
      margin: 0 auto;
      margin-top: 20px;
      display: flex;

      .el-button {
        margin-left: 10px;
      }
    }

    .tip {
      margin-top: 12px;
      text-align: center;
      color: var(--main-font-color);
      font-size: .75rem !important;
      transition-property: all;
      transition-duration: 0.6s;
    }
  }

  .loading,
  .loading>div {
    position: relative;
    box-sizing: border-box;
  }

  .loading {
    display: block;
    font-size: 0;
    color: #ababab;
  }

  .loading.la-dark {
    color: #cecece80;
  }

  .loading>div {
    display: inline-block;
    float: none;
    background-color: currentColor;
    border: 0 solid currentColor;
  }

  .loading {
    width: 54px;
    height: 18px;
  }

  .loading>div:nth-child(1) {
    animation-delay: -200ms;
  }

  .loading>div:nth-child(2) {
    animation-delay: -100ms;
  }

  .loading>div:nth-child(3) {
    animation-delay: 0ms;
  }

  .loading>div {
    width: 10px;
    height: 10px;
    margin: 4px;
    border-radius: 100%;
    animation: ball-pulse 1.5s ease infinite;
  }

  .loading.la-sm {
    width: 26px;
    height: 8px;
  }

  .loading.la-sm>div {
    width: 4px;
    height: 4px;
    margin: 2px;
  }

  .loading.la-2x {
    width: 108px;
    height: 36px;
  }

  .loading.la-2x>div {
    width: 20px;
    height: 20px;
    margin: 8px;
  }

  .loading.la-3x {
    width: 162px;
    height: 54px;
  }

  .loading.la-3x>div {
    width: 30px;
    height: 30px;
    margin: 12px;
  }

  @keyframes ball-pulse {

    0%,
    60%,
    100% {
      opacity: 1;
      transform: scale(1);
    }

    30% {
      opacity: 0.1;
      transform: scale(0.01);
    }
  }

  .codeBgc {
    background-color: #23241f;
  }
</style>

<style lang="scss">
  .hljs {
    background-color: #21252b !important;
  }

  .hljs-copy {
    font-size: 14px;
    line-height: 25px;
    top: 22px;
    right: 0%;
  }

  /* 语法高亮 */
  .hljs-container {
    width: 93% !important;
    margin-left: 20px;
    border-radius: 11px;
    position: relative;
    display: block;
    // width: 600px;
    padding: 0px 5px 2px;
    overflow-x: auto !important;
    line-height: 20px;
    text-align: left;
    background: #21252b;
    box-shadow: 0 10px 30px 0 rgb(0 0 0 / 40%);
  }

  // /** 3个点 */
  // .hljs-container::before {
  //     // position: absolute;
  //     // top: 10px;
  //     // left: 15px;
  //     // width: 12px;
  //     // height: 12px;
  //     // overflow: visible;
  //     // font-weight: 700;
  //     // font-size: 16px;
  //     // line-height: 12px;
  //     // white-space: nowrap;
  //     // text-indent: 75px;
  //     // background-color: #fc625d;
  //     // border-radius: 16px;
  //     // box-shadow: 20px 0 #fdbc40, 40px 0 #35cd4b;
  //     // content: attr(codetype);
  // }

  /** 滚动条 */
  :deep(.hljs) {
    overflow-x: auto;
  }

  :deep(.hljs::-webkit-scrollbar) {
    width: 12px !important;
    height: 12px !important;
  }

  :deep(.hljs::-webkit-scrollbar-thumb) {
    height: 30px !important;
    background: #d1d8e6;
    background-clip: content-box;
    border: 2px solid transparent;
    border-radius: 19px;
    opacity: 0.8;
  }

  :deep(.hljs::-webkit-scrollbar-thumb:hover) {
    background: #a5b3cf;
    background-clip: content-box;
    border: 2px solid transparent;
  }

  :deep(.hljs::-webkit-scrollbar-track-piece) {
    width: 30px;
    height: 30px;
    background: #333;
  }

  ::-webkit-scrollbar-button {
    display: none;
  }
</style>